﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EZMemoLib;
using System.IO;

namespace EZMemoLib
{
    public class BookBusiness
    {
        static BookBusiness _BookBusiness = null;
        public static BookBusiness Instance()
        {
            if (_BookBusiness == null)
            {
                _BookBusiness = new BookBusiness();
            }

            return _BookBusiness;

        }

        EZMemoEntities database = new EZMemoEntities();
        public List<MemoCategory> GetBookList(long parentID)
        {
            var list = database.MemoCategory.Where(c => c.CategoryLevel == (int)CategoryLevel.Book  );

            if (parentID > 0)
            {
                list = list.Where(c => c.ParentID == parentID);
            }
            return list.ToList ();
        }

        /// <summary>
        /// State the item count and save book information for categroy
        /// </summary>
        /// <param name="parentID"></param>
        /// <returns></returns>
        public int StatBookItemTotal(long bookID)
        {
            var cat = GetCategory(bookID);
            int count = database.MemoItem.Where(c => c.ItemStatus == 1 && c.Book == cat.CategoryID).Count();

            if (count > 0)
            {
                cat.ItemTotal = count;
                SaveCategory(cat);
            }

            return count;
        }


        public List<MemoCategory> GetLessonList(long parentID)
        {
            var list = database.MemoCategory.Where(c => c.CategoryLevel == (int)CategoryLevel.Lesson );

            if (parentID > 0)
            {
                list = list.Where(c => c.ParentID == parentID);
            }

            return list.ToList ();
        }

        public List<MemoCategory> GetLessonByNumber( string number)
        {
            var list = database.MemoCategory.Where(c => c.CategoryLevel == (int)CategoryLevel.Lesson);

            if (!string.IsNullOrEmpty ( number ))
            {
                list = list.Where(c => c.CategoryNumber == number);
            }

            return list.ToList ();
        }

        public MemoCategory GetLesson( long categoryID)
        {
            var list = database.MemoCategory.Where(c => c.CategoryID == categoryID);
            if (list.Count() > 0)
            {
                return list.First();
            }

            return null;
        }

        public MemoCategory GetCategory(long categoryID)
        {
            var list = database.MemoCategory.Where(c => c.CategoryID == categoryID);
            if (list.Count() > 0)
            {
                return list.First();
            }

            return null;
        }

        public int SaveCategory(MemoCategory category)
        {
            int rc = 0;

            if (category == null)
                return rc;

            MemoCategory cate = null;

            if (category.CategoryID > 0)
            {
                cate = database.MemoCategory.Where(c => c.CategoryID == category.CategoryID).FirstOrDefault();
            }

            if (cate == null)
            {
                if (category.CategoryNumber == null)
                {
                    category.CategoryNumber = category.CategoryName; 
                }
                database.AddToMemoCategory(category);
            }
            else
            {
                cate.CategoryID = category.CategoryID;
                cate.CategoryDesc = category.CategoryDesc;

                cate.CategoryName = category.CategoryName;
                cate.CategoryIndex = category.CategoryIndex;
                cate.CategoryLevel = category.CategoryLevel;
                cate.CategorySound = category.CategorySound;
                cate.ParentID = category.ParentID;
            }
            
            rc = database.SaveChanges();
            return rc;
        }

        public static int RemoveCategory( int categoryID)
        {
            int rc = 0;

            var database = new EZMemoEntities();
            var cat = database.MemoCategory.Where(c => c.CategoryID == categoryID).FirstOrDefault();

            if (cat != null)
            {
                database.MemoCategory.DeleteObject(cat);
                rc = database.SaveChanges();
            }

            return rc;
        }

        public int ImportFromLrc(long bookID, string sourceFolder)
        {
            int count = 0;
            string folder = sourceFolder;
            string TargetFolder = Context.FileFolderBook(bookID);

            DirectoryInfo di = new DirectoryInfo(folder);
            var files = di.GetFiles("*.lrc");
            count = files.Length;
            foreach (var file in files)
            {
                try
                {
                    string[] fileNameStringArray = file.Name.Split(new char[] { ' ', '.', '－' });
                    string lessonNumber = "";
                    string lessonName = "";
                    long lessonID = 0;
                    long lessonCategoryID = 0;

                    if (fileNameStringArray != null && fileNameStringArray.Length > 0)
                    {
                        lessonNumber = fileNameStringArray[0];
                        lessonName = file.Name.Substring(0, file.Name.Length - file.Extension.Length);

                        string text = file.OpenText().ReadToEnd();
                        long.TryParse(lessonNumber, out lessonID);
                        if (lessonID > 0)
                        {
                            //create lesson 
                            MemoCategory category = new MemoCategory
                            {
                                ParentID = bookID,
                                CategoryName = lessonName,
                                CategoryNumber = lessonNumber,
                                CategoryLevel = (int)CategoryLevel.Lesson,
                                CategoryStatus = (int)Status.Activited,
                                CategoryText = text,
                                CategoryDesc = lessonName,
                                ItemTotal = 0,
                                ItemDone = 0,
                                ItemDrill = 0,
                                ItemPlan = 10,
                                CategoryIndex = count + 1,
                                FrequentlyIndex = 0

                            };
                            SaveCategory(category);

                            var lessonList = GetLessonByNumber(lessonNumber);
                            if (lessonList != null && lessonList.Count > 0)
                            {
                                lessonCategoryID = lessonList[0].CategoryID;
                            }

                        }

                    }
                    var player = Player.Instance("", bookID);

                    var fs = file.OpenText();

                    int orderNumber = 1;
                    string line = fs.ReadLine();

                    List<MemoItem> items = new List<MemoItem>();
                    while (line != null)
                    {

                        string line1 = line;
                        string line2 = string.Empty;
                        line = fs.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                        {
                            line2 = line;
                        }
                        var part = Player.ParseVoicePartLrc(line1, line2);

                        if (part != null)
                        {
                            if (part.PartStart.TotalMilliseconds > 0)
                            {
                                string text = part.FileMark;
                                part.FileMark = "L";
                                var item = new MemoItem
                                {
                                    Book = bookID,
                                    Category = lessonCategoryID,
                                    ItemQuestion = text,
                                    ItemAnswer = text,
                                    ItemSound = Player.BuildVoicePart(part),
                                    ItemOrder = orderNumber,
                                    ItemName = "" + orderNumber,
                                    ItemStatus = (int)Status.Activited
                                };

                                player.SaveItem(item);
                                orderNumber++;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }

            }

            return count;
        }

        public int ImportMp3Files(long bookID, string sourceFolder)
        {
            int count = 0;
            string folder = sourceFolder;
            string TargetFolder = Context.FileFolderBook(bookID);
            DirectoryInfo di = new DirectoryInfo(folder);
            var files = di.GetFiles("*.mp3");
            count = files.Length;
            foreach (var file in files)
            {
                try
                {
                    string name = file.Name;
                    string[] fileNameStringArray = file.Name.Split(new char[] { ' ', '.', '－' });
                    if (fileNameStringArray != null && fileNameStringArray.Length > 0)
                    {
                        name = fileNameStringArray[0];
                    }

                    string targeFile = string.Format(@"{0}\{1}.mp3", TargetFolder, name);
                    FileOp.CopyFile(file.FullName, targeFile, true);
                    count++;
                }
                catch
                { }
            }

            return count;
        }

        public void ImportFromBook( long bookID)
        {
            var items = MemoLib.MemoBook.GetItemListAll((int)bookID);

            foreach (var item in items)
            {
                ImportItem(item);
            }
        }

        public int ImportItem(MemoLib.MemoItem item)
        {
            int rc = 0;
            if (item == null)
                return rc;

            MemoItem ri = database.MemoItem.Where(c => c.ItemID == item.ItemID).FirstOrDefault();

            if (ri == null)
            {
                //ri.ItemID = item.ItemID;
                ri.Category = item.Category;
                ri.Book = item.Book;
                ri.ItemAnswer = item.ItemAnswer;
                ri.ItemDesc = item.ItemDesc;
                ri.ItemStatus = item.ItemStatus;
                ri.ItemFlow = item.ItemFlow;

                ri.ItemName = item.ItemName;
                ri.ItemOrder = item.ItemOrder;
                ri.ItemPicture = item.ItemPicture;
                ri.ItemQuestion = item.ItemQuestion;
                ri.ItemRelation = item.ItemRelation;
                ri.ItemSound = item.ItemSound;
                ri.ItemSource = item.ItemSource;
                ri.ItemType = item.ItemType;
                ri.ItemVideo = item.ItemVideo;

                database.AddToMemoItem(ri);
            }
            else
            {
                ri.ItemID = item.ItemID;
                ri.Category = item.Category;
                ri.Book = item.Book;
                ri.ItemAnswer = item.ItemAnswer;
                ri.ItemDesc = item.ItemDesc;
                ri.ItemStatus = item.ItemStatus;
                ri.ItemFlow = item.ItemFlow;

                ri.ItemName = item.ItemName;
                ri.ItemOrder = item.ItemOrder;
                ri.ItemPicture = item.ItemPicture;
                ri.ItemQuestion = item.ItemQuestion;
                ri.ItemRelation = item.ItemRelation;
                ri.ItemSound = item.ItemSound;
                ri.ItemSource = item.ItemSource;
                ri.ItemType = item.ItemType;
                ri.ItemVideo = item.ItemVideo;
            }

            rc = database.SaveChanges();
            return rc;
        }
    }
}
